package com.zzzy.cont.controller.deptcon;

import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.cont.dao.entity.ConFileHistory;
import com.zzzy.cont.service.ConFileHistoryService;
import com.zzzy.cont.vo.contract.my.ConFileHistoryRes;
import com.zzzy.cont.vo.pageoffice.OpenOfficeFileRes;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;

@Tag(name = "部门合同-历史版本", description = "con505")
@Validated
@RestController
@RequestMapping("/con/deptConFileHistory")
public class DeptConFileHistoryController {

    @Resource
    private ConFileHistoryService conFileHistoryService;

    @Operation(summary = "列表")
    @GetMapping(value = "/list/{conId}")
    @Parameter(name = "conId", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:dept:page')")
    public AjaxResult<List<ConFileHistoryRes>> list(@NotNull(message = "合同ID不能为空") @PathVariable("conId") Long conId) {
        List<ConFileHistoryRes> docHistoryList = conFileHistoryService.getConHistoryFileList(conId);
        return AjaxResult.success(docHistoryList);
    }

    @GetMapping(value = "/getPageOfficeFile/{id}")
    @Operation(summary = "打开文件")
    @Parameter(name = "id", description = "合同历史版本ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:dept:page')")
    public AjaxResult<OpenOfficeFileRes> getPageOfficeFile(@NotNull(message = "合同历史版本ID不能为空") @PathVariable("id") Long id) {
        String openFileUrl = "/con/processConFileHistory/getConFileHistoryStream/" + id;
        OpenOfficeFileRes openOfficeFileRes = conFileHistoryService.getPageOfficeResByConId(id, openFileUrl);
        return AjaxResult.success(openOfficeFileRes);
    }

    @GetMapping(value = "/getConFileHistoryStream/{id}")
    @Operation(summary = "获取文件流")
    @Parameter(name = "id", description = "合同历史版本ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:dept:page')")
    public void getConFileHistoryStream(@NotNull(message = "合同历史版本ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        ConFileHistory conFileHistory = conFileHistoryService.getConFileHistoryById(id);
        FileUtil.outputFileStream(response, conFileHistory.getFileBlob(), conFileHistory.getEdition() + "." + FileUtil.getFileType(conFileHistory.getFileBlob()));
    }
}
